package com.zzyl.nursing.service.impl;

import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.domain.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * 设备维护表Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-19
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;
    @Autowired
    private Client client;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String PRODUCT_LIST_KEY = "IOT_KEY_LIST";



//    /**
//     * 查询设备维护表
//     *
//     * @param id 设备维护表主键
//     * @return 设备维护表
//     */
//    @Override
//    public Device selectDeviceById(Long id)
//    {
//        return getById(id);
//    }

    /**
     * 查询设备维护表列表
     *
     * @param device 设备维护表
     * @return 设备维护表
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() throws Exception {
        QueryProductListRequest queryProductListRequest = new QueryProductListRequest();
        queryProductListRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        queryProductListRequest.setCurrentPage(1);
        queryProductListRequest.setPageSize(100);
        QueryProductListResponse response = client.queryProductList(queryProductListRequest);
        log.info("查询产品列表返回:{}", JSONUtil.toJsonStr(response.getBody().getData().getList().getProductInfo()));
        try {
            String jsonStr = JSONUtil.toJsonStr(response.getBody().getData().getList().getProductInfo());
            redisTemplate.opsForValue().set(PRODUCT_LIST_KEY, jsonStr);
        } catch (Exception e) {
            log.error("同步产品列表失败", e);
        }
    }

    /**
 * 注册设备
 *
 * @param deviceDto 设备数据传输对象，包含设备相关信息
 */
@Override
public void register(DeviceDto deviceDto) {
    // 检查设备是否已经注册
    long count = super.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName())); // 查询本地数据库中是否存在相同IotId的设备
    if (count > 0) { // 如果存在相同IotId的设备
        throw new BaseException("设备已存在"); // 抛出异常，表示设备已存在
    }

    // 向IoT平台注册设备
    RegisterDeviceRequest request = new RegisterDeviceRequest(); // 创建注册设备请求对象
    request.setProductKey(deviceDto.getProductKey());
    request.setDeviceName(deviceDto.getDeviceName());
    request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
    RegisterDeviceResponse response = null; // 初始化响应对象
    try {
        response = client.registerDevice(request); // 调用客户端方法向IoT平台注册设备，并获取响应
    } catch (Exception e) { // 捕获注册过程中可能出现的异常
        log.error("设备注册到阿里云失败", e); // 记录错误日志
        throw new BaseException("设备注册到IoT平台失败"); // 抛出自定义异常，表示注册失败
    }
    log.info("注册设备返回:{}", JSONUtil.toJsonStr(response)); // 记录注册设备的返回结果


    if (!response.getBody().getSuccess()){
        log.error("设备注册失败" );
        throw new BaseException("设备注册失败");
    }

    //获取iOTId
    String iotId = response.getBody().getData().getIotId();
    //保存产品到本地数据库
    Device device = new Device();
    BeanUtils.copyProperties(deviceDto, device);
    device.setIotId(iotId);

    //处理copy不了的字段
    device.setCreateTime(new Date());
    device.setBindingLocation(deviceDto.getBindingLocation()+"");

    try {
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        queryProductRequest.setProductKey(deviceDto.getProductKey());
        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryProductResponse queryProductResponse = client.queryProduct(queryProductRequest);
        device.setProductName(queryProductResponse.getBody().getData().getProductName());
        super.save(device);
    } catch (Exception e) {
        log.error("获取产品名称或者保存本地失败",e);
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.setIotId(iotId);
        try {
            log.error("回滚iot平台的新增的设备");
            client.deleteDevice(deleteDeviceRequest);
        } catch (Exception e1) {
            log.error("因为保存本地数据库失败,去IOT平台删除设备失败了,需要人工处理", e1);
        }
    }
}

    /**
     * 获取设备详情
     *
     * @param deviceVo
     * @return
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceVo deviceVo) {
        //查询iot平台设备详情
        QueryDeviceDetailRequest detailRequest = new QueryDeviceDetailRequest();
        detailRequest.setIotId(deviceVo.getIotId());
        detailRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        detailRequest.setProductKey(deviceVo.getProductKey());

        QueryDeviceDetailResponse queryResponse = null;

        try {
            queryResponse  = client.queryDeviceDetail(detailRequest);
        } catch (Exception e) {
            log.error("查询设备数据失败",e);
            throw new BaseException("查询设备数据失败");
        }
        //查询表中的数据
        Device device = super.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceVo.getIotId()));
        if (device == null){
            throw new BaseException("从数据库获取数据异常");
        }
        BeanUtils.copyProperties(device, deviceVo);

        //设置设备详情
        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = queryResponse.getBody().getData();
        BeanUtil.copyProperties(data, deviceVo, CopyOptions.create().ignoreNullValue());
        return deviceVo;
    }

    /**
     * 查询物模型
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) throws Exception {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        try {
            QueryThingModelPublishedResponse response = client.queryThingModelPublished(request);
            return AjaxResult.success(response.getBody().getData());
        } catch (Exception e) {
            log.error("查询物模型失败", e);
            return AjaxResult.error("查询物模型异常");
        }

    }


    /**
     * 查询产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String ProductStr = redisTemplate.opsForValue().get(PRODUCT_LIST_KEY);
        return JSONUtil.toList(ProductStr, ProductVo.class);
    }

    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        try {
            QueryDevicePropertyStatusResponse response = client.queryDevicePropertyStatus(request);
            return AjaxResult.success(response.getBody().getData());
        } catch (Exception e) {
            log.error("查询设备属性失败", e);
            return AjaxResult.error("查询设备属性失败");
        }
    }


//    /**
//     * 新增设备维护表
//     *
//     * @param device 设备维护表
//     * @return 结果
//     */
//    @Override
//    public int insertDevice(Device device)
//    {
//        return save(device)?1:0;
//    }
//
//    /**
//     * 修改设备维护表
//     *
//     * @param device 设备维护表
//     * @return 结果
//     */
//    @Override
//    public int updateDevice(Device device)
//    {
//        return updateById(device)?1:0;
//    }
//
//    /**
//     * 批量删除设备维护表
//     *
//     * @param ids 需要删除的设备维护表主键
//     * @return 结果
//     */
//    @Override
//    public int deleteDeviceByIds(Long[] ids)
//    {
//        return removeByIds(Arrays.asList(ids))?1:0;
//    }
//
//    /**
//     * 删除设备维护表信息
//     *
//     * @param id 设备维护表主键
//     * @return 结果
//     */
//    @Override
//    public int deleteDeviceById(Long id)
//    {
//        return removeById(id)?1:0;
//    }

}
